package com.level2app.di.retrofit;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.level2app.R;
import com.level2app.utils.ToastHelper;

import java.io.IOException;
import java.util.Objects;

import io.reactivex.subscribers.ResourceSubscriber;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

public abstract class BaseNetCallback<T> extends ResourceSubscriber<T> {
    @Override
    public void onNext(T tBaseModel) {
        onSuccess(tBaseModel);
    }

    @Override
    public void onError(Throwable paramThrowable) {
        if ((paramThrowable instanceof HttpException)) {
            try {
                //{"message":"User does not exist"}
                //获取message
                HttpException exception = (HttpException) paramThrowable;
                ResponseBody body = Objects.requireNonNull(exception.response()).errorBody();
                assert body != null;
                JsonObject jsonObject = JsonParser.parseString(body.string()).getAsJsonObject();
                String message = jsonObject.get("message").getAsString();
                onError(message);
            } catch (IOException e) {
                onError(paramThrowable.getMessage());
                throw new RuntimeException(e);
            } catch (Exception e) {
                onError(paramThrowable.getMessage());
            }
        } else {
            onError(paramThrowable.getMessage());
        }
    }

    @Override
    public void onComplete() {
    }

    public abstract void onSuccess(T baseModel);

    public void onError(String message) {
        ToastHelper.showToastAndImage(message, R.mipmap.icon_toast_error);
    }
}